
import { HomeOutlined } from "@ant-design/icons";
import { cloneDeep } from "lodash-es";
import Link from "next/link";
import * as icons from "@ant-design/icons";
import { Menu } from "@prisma/client";

export type MenusItem = {
  label: React.ReactNode;
  key: React.Key;
  icon?: React.ReactNode;
  children?: MenusItem[];
};
function getItem(
  label: React.ReactNode,
  key?: React.Key | null,
  icon?: React.ReactNode,
  children?: MenusItem[]
): MenusItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenusItem;
}
export const geneRateMenuTree = (
  arr: Menu[],
  showParent = false
): MenusItem[] => {
  //将id做为对象的键名，整个对象做为键值 来生成新的
  arr = cloneDeep(arr);
  const treeList = arr.reduce((prev, cur) => {
    prev[cur.id] = cur;
    return prev;
  }, {} as any);

  //通过引用类型原理实现
  const result = arr.reduce((prev, cur: any) => {
    const pid = cur.parentId || 0;
    // pid为0的就找不到父对象，找到当前cur的父对象
    // 对象的浅拷贝，引用关系存在，在后面处理parent的时候也会导致cur的改变，达到递归的效果
    const parent = treeList[pid];
    cur.key = cur.id;
    if (parent) {
      // parent和cur存在引用关系
      parent.children ? parent.children.push(cur) : (parent.children = [cur]);
    } else if (!pid) {
      // 没有父对象，则此cur为树的根元素
      prev.push(cur);
    }
    return prev;
  }, [] as any);

  const setCom = (list: any[], parentPath = "") => {
    list.forEach((it) => {
      let Icon = (icons as any)[it.icon];

      it.icon = it.icon ? <Icon></Icon> : <HomeOutlined />;
      it.key = `${parentPath}${it.path}`;
      it.label = <Link href={it.key}>{it.name}</Link>;
      if (!showParent) {
        delete it.parentId;
        delete it.createdAt;
      }

      if (it.children && it.children.length > 0) {
        // 修复父级重定向问题
        it.label = it.name;
        setCom(it.children, it.key);
      }
    });
  };
  setCom(result);
  return result;
};

export const getAllPath = (arr: Menu[]): string[] => {
  // console.log(1);
  let obj = arr.reduce((pre: any, cu: Menu) => {
    pre[cu.id] = cu;
    return pre;
  }, {} as any);
  const getPath = (it: Menu, path: string = ""): string => {
    path = `${it.path}${path}`;
    if (it.parentId) {
      return getPath(obj[it.parentId], path);
    }
    return path;
  };
  let paths = arr.map((it: Menu) => {
    return getPath(it);
  });
  return paths;
};
